package com.github.baichuan.application.scaffold.rest.security;

import com.github.baichuan.web.dto.Result;
import lombok.Builder;

import java.util.regex.Pattern;

/**
 * 密码强度
 */
@Builder
public class PasswordStrength {
    private int minLength;

    private boolean requiredDigit;

    private boolean requiredLowercase;

    private boolean requiredUppercase;

    private boolean requiredSymbol;

    private static final Pattern DIGIT_REGEX = Pattern.compile("[0-9]");

    private static final Pattern LOWERCASE_REGEX = Pattern.compile("[a-z]");

    private static final Pattern UPPERCASE_REGEX = Pattern.compile("[A-Z]");

    /**
     * 密码强度验证
     * @return
     */
    public Result validate(String password){
        if(password.trim().length() < minLength){
            return Result.fail("密码长度最少" + minLength + "位");
        }

        int digits = 0;
        int lowercase = 0;
        int uppercase = 0;
        int symbol = 0;

        for(int i = 0; i < password.length(); i++){
            String charactor = String.valueOf(password.charAt(i));

            if(DIGIT_REGEX.matcher(charactor).find()){
                digits++;
                continue;
            }

            if(LOWERCASE_REGEX.matcher(charactor).find()){
                lowercase++;
                continue;
            }

            if(UPPERCASE_REGEX.matcher(charactor).find()){
                uppercase++;
                continue;
            }

            symbol++;
        }

        if(requiredLowercase && lowercase == 0){
            return Result.fail("密码强度不足" + claim());
        }

        if(requiredUppercase && uppercase == 0){
            return Result.fail("密码强度不足" + claim());
        }

        if(requiredDigit && digits == 0){
            return Result.fail("密码强度不足" + claim());
        }

        if(requiredSymbol && symbol == 0){
            return Result.fail("密码强度不足" + claim());
        }

        return Result.success("密码强度符合要求");
    }

    /**
     * 获取密码强度要求
     * @return
     */
    public String claim(){
        StringBuilder builder = new StringBuilder();
        builder.append("密码需要包含");


        if(requiredLowercase){
            builder.append("小写字母、");
        }
        if(requiredUppercase){
            builder.append("大写字母、");
        }
        if(requiredDigit){
            builder.append("数字、");
        }
        if(requiredSymbol){
            builder.append("特殊符号、");
        }
        builder.deleteCharAt(builder.length() - 1);

        return builder.toString();
    }
}
